package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.RedisLock;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import org.apache.logging.log4j.message.ReusableMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.LocaleResolver;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    private final StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedisLock redisLock;
    @Autowired
    private LocaleResolver localeResolver;

    public ShopServiceImpl(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }



    //互斥锁的时候，redis的数据类型不用改
    @Override
    public Result queryWithMutex(Long id) {
        String cacheShopKey = CACHE_SHOP_KEY  +id ;
        //根据id查询shop
        String s = stringRedisTemplate.opsForValue().get(cacheShopKey);

        Shop bean = JSONUtil.toBean(s, Shop.class);
        if(s!=null){
            return Result.ok(bean);
        }
        String lockKey = LOCK_SHOP_KEY + id;
        Shop shop = null;


        try {
            boolean isLock =  redisLock.tryLock(lockKey);
            // 4.2 判断否获取成功
            if(!isLock){
                //4.3 失败，则休眠重试
                Thread.sleep(50);
                return queryWithMutex(id);
            }
            shop = getById(id);
            if(shop == null){
                stringRedisTemplate.opsForValue().set(cacheShopKey,"",LOCK_SHOP_TTL, TimeUnit.MINUTES);
                return Result.ok();//第一版本失误
            }

            stringRedisTemplate.opsForValue().set(cacheShopKey,JSONUtil.toJsonStr(shop),LOCK_SHOP_TTL, TimeUnit.MINUTES);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            redisLock.unlock(lockKey);
        }

        return Result.ok(shop);//第一版本失误

    }

    /** key = shop_id+  , value：shop 对象
     * 1 根据shopId首先查询redis中的数据
     * 2 如果没有再查找数据库的数据
     * 3 数据库没有，返回错误
     * 4 有的话， 先写入 reids  ，再返回
     * 5 根据service层的curd查找，使用了mybatis—plus
     * 6 为解决缓存击穿问题，如果在数据库查询中，没有查到结果，那么在redis中设置null
     * 同时在 后续的查询工作中，如果查redis为null返回
     */
    @Override
    public Result queryById(Long id) {
        Shop shop = queryWithLogicalExpire(id);
        return Result.ok(shop);
    }





    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    public Shop queryWithLogicalExpire( Long id ) {
        String key = CACHE_SHOP_KEY + id;
        // 1.从redis查询商铺缓存
        String json = stringRedisTemplate.opsForValue().get(key);
        // 2.判断是否存在
        if (StrUtil.isBlank(json)) {
            // 3.不存在，直接返回
            return null;
        }
        // 4.命中，需要先把json反序列化为对象
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        // 5.判断是否过期
        if(expireTime.isAfter(LocalDateTime.now())) {
            // 5.1.未过期，直接返回店铺信息
            return shop;
        }
        // 5.2.已过期，需要缓存重建
        // 6.缓存重建
        // 6.1.获取互斥锁
        String lockKey = LOCK_SHOP_KEY + id;
        boolean isLock = redisLock.tryLock(lockKey);
        // 6.2.判断是否获取锁成功
        if (isLock){
            CACHE_REBUILD_EXECUTOR.submit( ()->{

                try{
                    rebuildCache(id);

                    //重建缓存

                }catch (Exception e){
                    throw new RuntimeException(e);
                }finally {
                    redisLock.unlock(lockKey);
                }
            });
        }
        // 6.4.返回过期的商铺信息
        return shop;
    }

    private void rebuildCache(Long shopId) {
        System.out.println("重建缓存: " + shopId);

        // 模拟数据库查询
        Shop shop = getShopFromDB(shopId);
        if (shop == null) {
            return;
        }

        // 创建 RedisData 并设置逻辑过期时间（1小时后）
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusHours(1));

        // 更新 Redis 缓存
        String key = CACHE_SHOP_KEY + shopId;
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));

        System.out.println("缓存更新成功: " + shopId);
    }

    /**
     * 模拟数据库查询
     */
    private Shop getShopFromDB(Long shopId) {
        // 实际业务中这里应该是数据库查询
        return query().eq("id", shopId).one();
    }

    //
    //    (第一版)@Override
//    public Result queryById(Long id) {(第一版)
//        String cacheShopKey =CACHE_SHOP_KEY +id ;
//        //根据id查询shop
//        String s = stringRedisTemplate.opsForValue().get(cacheShopKey);
//
//        Shop bean = JSONUtil.toBean(s, Shop.class);
//        if(s!=null){
//            return Result.ok(bean);
//        }
//        Shop shop = null;
//            shop = getById(id);
//            if(shop == null){
//                stringRedisTemplate.opsForValue().set(cacheShopKey,"",LOCK_SHOP_TTL, TimeUnit.MINUTES);
//                return Result.ok();//第一版本失误
//            }
//
//            stringRedisTemplate.opsForValue().set(cacheShopKey,JSONUtil.toJsonStr(shop),LOCK_SHOP_TTL, TimeUnit.MINUTES);
//
//
//        return Result.ok(shop);//第一版本失误
//
//    }


    /**
     * 判断id是不是为空
     * 根据店铺id去更新数据库，通过service层的curd接口
     */
    @Override
    public Result update(Shop shop) {
        Long id = shop.getId();
        if(id == null){
            return Result.fail("店铺id不能为空");
        }
        updateById(shop);
        stringRedisTemplate.delete(LOCK_SHOP_KEY+id);
        return Result.ok();

    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        // 1.判断是否需要根据坐标查询
        if (x == null || y == null) {
            // 不需要坐标查询，按数据库查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            List<Shop> records = page.getRecords();
            // 返回数据
            return Result.ok(page.getRecords());
        }
        // 2.计算分页参数
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;
        String key = SHOP_GEO_KEY + typeId;
        //
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo().search(
                key,
                GeoReference.fromCoordinate(x, y),
                new Distance(5000),
                RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end)
        );
        if (results == null) {
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if (list.size() <= from) {
            // 没有下一页了，结束
            return Result.ok(Collections.emptyList());
        }
        //id存店铺id，distancemap存id和距离
        List<Long> ids = new ArrayList<>(list.size());
        Map<String, Distance> distanceMap = new HashMap<>(list.size());
        list.stream().skip(from).forEach(item -> {
            String shopIdStr = item.getContent().getName();
            ids.add(Long.valueOf(shopIdStr));
            Distance distance = item.getDistance();
            distanceMap.put(shopIdStr, distance);
        });
        String join = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids)
                .last("order by filed( id ," + join + ")")
                .list();
        for (Shop shop : shops) {
            shop.setDistance(distanceMap.get(String.valueOf(shop.getId())).getValue());
        }
        // 6.返回
        return Result.ok(shops);
    }
}
